---
import type { GetStaticPaths, Page } from 'astro'
import type { CollectionEntry } from 'astro:content'

import { Paginator, PostPreview } from 'astro-pure/components/pages'
import { getBlogCollection, getUniqueTags, sortMDByDate } from 'astro-pure/server'
import { Button } from 'astro-pure/user'
import PageLayout from '@/layouts/BaseLayout.astro'
import config from '@/site-config'

export const prerender = true

export const getStaticPaths: GetStaticPaths = async ({ paginate }) => {
  const allPosts = await getBlogCollection()
  const allPostsByDate = sortMDByDate(allPosts)
  const uniqueTags = getUniqueTags(allPostsByDate)

  return uniqueTags.flatMap((tag) => {
    const filterPosts = allPostsByDate.filter((post) => post.data.tags.includes(tag))
    return paginate(filterPosts, {
      pageSize: config.content.blogPageSize,
      params: { tag }
    })
  })
}

interface Props {
  page: Page<CollectionEntry<'blog'>>
}

const { page } = Astro.props
const { tag } = Astro.params

const meta = {
  description: `View all posts with the tag - ${tag}`,
  title: `Tag: ${tag}`
}

const paginationProps = {
  ...(page.url.prev && {
    prevUrl: {
      text: `← 上一页`,
      url: page.url.prev
    }
  }),
  ...(page.url.next && {
    nextUrl: {
      text: `下一页 →`,
      url: page.url.next
    }
  })
}
---

<PageLayout {meta}>
  <Button title='返回' href='/blog' variant='back' />
  <main class='mt-6 lg:mt-10'>
    <div id='content-header' class='animate'>
      <h1 class='mb-6 flex items-end gap-x-2 text-3xl font-medium'>
        标签:
        <span class='text-2xl'>#{tag}</span>
      </h1>
    </div>

    <section id='content' class='animate' aria-label='Blog post list'>
      <ul class='flex flex-col gap-y-3 text-start'>
        {page.data.map((post) => <PostPreview as='h2' {post} detailed />)}
      </ul>
      <Paginator {...paginationProps} />
    </section>
  </main>
</PageLayout>
